<?php
class UserController extends AppController {

	var $name = 'User';

	var $helpers = array('Time', 'Lemur');

	function beforeFilter() {
		parent::beforeFilter();
	}

	function index($login = null, $action = null) {
		$data =  false;

		if ($login) {
			$uid = $this->User->field('id', array('login'=>$login));
			if ($uid) {

				$this->set('login', $login);

				$guest_id = $this->Auth->user('id');

				if ($uid === $guest_id) {
					$this->set('self', 1);
				}

				if (isset($this->data['Message']) && $guest_id) {
					$this->data['Message']['from_id'] = $guest_id;
					$this->data['Message']['to_id'] = $uid;
					if ($this->__message($this->data)) {
						$this->redirect('/user/'. $login);
					}
				}

				$perms = $this->__permitions($uid);	

				$conditions = array('Foto.user_id' => $uid, 'Fotopreview.scale' => 580);

				if ($action === 'message' && $guest_id) {
					$action = null;
					$this->set('message', 1);
				}
				
				if ($action === 'fotos' && $perms['fotos']) {
					$this->loadModel('Fotopreview');
					$this->paginate = array(
						'fields' => array('path', 'Foto.alt', 'Foto.hash'),
						'conditions'=>$conditions,
						'recursive'=>1,
						'limit'=>1,
						'order'=>'Foto.status DESC'
					);
					$data['fotos'] = $this->paginate('Fotopreview');
					$this->set($data);
					$this->render('fotos');
				}

				if ($action === null && $perms['account']) {
					$data = $this->User->getData($uid);
//pr ($data);
					$this->set($data);
				}
//pr ($data);

				$this->set('perms', $perms);
			}

		}

	}

	function __permitions($uid) {
		$perms_ = array();
		$perms	= $this->User->Privacy->getPermition($uid);

		if (!empty($perms[1])) {
			if ($this->Auth->isAuthorized()) {
				$auth = 1;
			} else {
				$auth = 0;
			}

			foreach ($perms[1] as $k => $v) {
				$perms_[$k] = $auth;
			}
		}

		if (!empty($perms[0])) {
			$perms_ = array_merge($perms[0], $perms_);
		}

		return $perms_;
	}

	function __message($data) {
		$return = false;
		$this->loadModel('Message');
#pr ($data);
		if ($this->Message->sendMessage($data)) {
			$this->Session->setFlash('сообщение отправленно');
			$return = true;
		}
		return $return;
	}

	function __fotos() {

	}

	function __account() {

	}
}
?>
